package com.sunwayworld.basemodule.basedata.codes.validator;

import com.sunwayworld.framework.database.sql.Order;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.validator.data.DataValidator;
import com.sunwayworld.module.sys.code.bean.CoreCodeBean;
import com.sunwayworld.module.sys.code.bean.CoreCodeCategoryBean;
import com.sunwayworld.module.sys.code.service.CoreCodeCategoryService;
import com.sunwayworld.module.sys.code.service.CoreCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Iterator;
import java.util.List;

@Repository
public class LimsCodeInsertableValidator implements DataValidator {
    @Autowired
    private CoreCodeService codeService;
    @Autowired
    private CoreCodeCategoryService codeCategoryService;

    public LimsCodeInsertableValidator() {
    }

    public boolean doValid(Object... args) {
        RestJsonWrapperBean wrapper = (RestJsonWrapperBean) args[0];
        CoreCodeBean code = wrapper.parseUnique(CoreCodeBean.class);
        List<CoreCodeBean> sameCodeCategoryList = this.codeService.selectListByFilter(SearchFilter.instance().match("CODECATEGORYID", code.getCodeCategoryId()).filter(MatchPattern.EQ), new Order[0]);
        Iterator<CoreCodeBean> iterator = sameCodeCategoryList.iterator();

        CoreCodeCategoryBean codeCategory = this.codeCategoryService.selectDetail(code.getCodeCategoryId());
        // 如果查询到是系统选项不允许新增
        if (codeCategory != null && "sys".equals(codeCategory.getCodeClassId())) {
            this.addConstraintViolation("CORE.MODULE.SYS.CODES.TIP.CANNOT_INSERT_SYS_CODE");
            return false;
        }
        // 如果存在同一分类下的选项，查找是否有编码相同的
        if (iterator.hasNext()) {
            while (iterator.hasNext()) {
                CoreCodeBean t = iterator.next();
                if (t.getCode().equals(code.getCode())) {
                    // 查找到编码相同的就返回校验失败
                    this.addConstraintViolation("CORE.MODULE.SYS.CODES.TIP.CODEDUPLICATED");
                    return false;
                }
            }
        }
        // 去掉添加选项时选项名称不能重复的限制
        return true;
    }
}
